import {
  indexApi
} from '../../../api/index';
import {
  request
} from '../../../utils/request';
import Toast from '@vant/weapp/toast/toast';
Page({
  data: {
    defaultData: {
      title: "订单详情", // 导航栏标题
      imageSrc: "/images/back.png",
      isBackToPreviousPage: true
    },
    order: {},
    orderId: null,
    isAllExpanded: false, // 用于记录是否全部展开
    orderList: [],
    activeNames: [],
    checked: true,
    selectedDate: '', //日期
    showTime: false, //日期弹框显示
    minDate: new Date().getTime(),
    address: "", //地址
    agree: true, //协议政策
    addReduce: 0, //附加费用
    totalQuantity: 0, // 总数量
    totalPrice: 0, // 总价
    serviceProviderStatus: 0, //工人3或者不是3就是客户
    status: null, //订单状态
    payWay:"2"
  },
  onLoad(options) {
    if (options.order) {
      const order = JSON.parse(decodeURIComponent(options.order));
      console.log("orderorder====", order);
      const selectedAddressObj = order.address;
      const selectedAddress = `${selectedAddressObj.province} ${selectedAddressObj.city} ${selectedAddressObj.area} ${selectedAddressObj.detail}`;
      console.log("selectedAddress", selectedAddress);
      this.setData({
        order,
        orderId: order.orderId,
        orderList: order.rooms,
        address: selectedAddress,
        status: order.status
      });
      this.calculateTotals();
      console.log("Received order:", this.data.orderList);
    } else {
      console.error("options.order is empty or undefined");
    }

    const serviceProviderStatus = wx.getStorageSync('serviceProviderStatus');
    this.setData({
      serviceProviderStatus
    });
    console.log("serviceProviderStatus", this.data.serviceProviderStatus);
  },
  onShow() {
    console.log("onShow executed");
  },
  onReady() {
    console.log("onReady executed");
  },
  backOrder() {
    wx.navigateBack({
      delta: 1
    });
  },

  // 展开/折叠单个面板
  onChange(event) {
    this.setData({
      activeNames: event.detail,
      isAllExpanded: event.detail.length === this.data.orderList.length
    });
  },

  // 展开/折叠全部面板
  toggleExpandAll() {
    if (this.data.isAllExpanded) {
      // 全部折叠
      this.setData({
        activeNames: [],
        isAllExpanded: false
      });
    } else {
      // 全部展开
      const allPanelNames = this.data.orderList.map(order => Number(order.orderRoomId));
      this.setData({
        activeNames: allPanelNames,
        isAllExpanded: true
      });
    }
  },

  // 计算各房间和所有房间的总价和总数量
  calculateTotals() {
    let totalQuantity = 0;
    let totalPrice = 0;
    const updatedOrderList = this.data.orderList.map(room => {
      const roomTotal = room.children.reduce((acc, item) => {
        acc.totalQuantity += item.count;
        acc.totalPrice += item.count * item.productPrice;
        return acc;
      }, {
        totalQuantity: 0,
        totalPrice: 0
      });

      totalQuantity += roomTotal.totalQuantity;
      totalPrice += roomTotal.totalPrice;

      return {
        ...room,
        roomTotalQuantity: roomTotal.totalQuantity,
        roomTotalPrice: roomTotal.totalPrice.toFixed(2) // 保留两位小数
      };
    });

    this.setData({
      orderList: updatedOrderList,
      totalQuantity,
      totalPrice: totalPrice.toFixed(2) // 保留两位小数
    });
  },

  //选择时间
  selectedTime() {
    console.log("“收到v产生的VS的");
    this.setData({
      showTime: true
    });
  },
  onConfirm(event) {
    const timestamp = event.detail; // 获取时间戳
    const date = new Date(timestamp); // 使用时间戳创建Date对象
    const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`; // 格式化日期和时间
    this.setData({
      showTime: false,
      selectedDate: formattedDate // 更新selectedDate为格式化后的日期和时间
    });
  },

  onCancel() {
    this.setData({
      showTime: false
    });
  },

  // 附加费用增加
  addChange() {
    this.setData({
      addReduce: this.data.addReduce + 1
    });
    this.calculateTotals();
  },

  // 附加费用减少
  reduceChange() {
    if (this.data.addReduce > 0) {
      this.setData({
        addReduce: this.data.addReduce - 1
      });
      this.calculateTotals();
    }
  },
  onProtocol(event) {
    this.setData({
      agree: event.detail,
    });
  },

  //确认接单
  async ConfirmOrder() {
    const {
      checked,
      agree,
      selectedDate,
      orderList,
    } = this.data;
    const orderId = orderList[0].orderId
    const reqTemplate = {
      orderId: orderId,
      appointmentDate: selectedDate
    }
    if (!selectedDate) {
      Toast('请输入时间');
      return;
    }

    // 检查 checked 是否为 true
    if (!checked) {
      Toast('请勾选复选框');
      return;
    }
    if (agree == false) {
      Toast('请同意协议和政策');
      return;
    }else{
      try {
        const res = await request({
          url: indexApi.orderGrabbingApi(),
          method: "POST",
          data: reqTemplate
        });
        console.log(res);
        wx.switchTab({
          url: '/pages/order/index',
        });
      } catch (error) {
        console.error("Error:", error);
      }
    }
 
  },

  //确认上门
  async ConfirmDoorService() {
    const reqTemplate = {
      orderId: this.data.order.orderId
    }
    if (this.data.agree == false) {
      Toast('请同意协议和政策');
      return;
    }else{
      try {
        const res = await request({
          url: indexApi.doorService(),
          method: "POST",
          data: reqTemplate
        });
        console.log(res);
        wx.switchTab({
          url: '/pages/order/index',
        });
      } catch (error) {
        console.error("Error:", error);
      }
    }
  
  },

  // 服务结束
  async ServiceCompleted() {
    const reqTemplate = {
      orderId: this.data.order.orderId
    }
    if (this.data.agree == false) {
      Toast('请同意协议和政策');
      return;
    }else{
      try {
        const res = await request({
          url: indexApi.serviceEnd(),
          method: "POST",
          data: reqTemplate
        });
        console.log(res);
        wx.switchTab({
          url: '/pages/order/index',
        });
      } catch (error) {
        console.error("Error:", error);
      }
    }
    
  },

  //跳转到评价页面
  toEvaluate() {
    const orderString = encodeURIComponent(JSON.stringify(this.data.order));
    if (this.data.agree == false) {
      Toast('请同意协议和政策');
      return;
    }else{
      wx.navigateTo({
        url: `/packageOrder/pages/evaluate/index?order=${orderString}`,
      })
    }
    
  },

  //选择付款方式
  paymentChange(event){
    console.log("付款方式",event.detail);
    this.setData({
      payWay:event.detail
    })
  },

  //支付下单
  async placeOrder() {
    const reqTemplate = {
      orderId: this.data.orderId,
      payWay:this.data.payWay
    }
    if (this.data.agree == false) {
      Toast('请同意协议和政策');
      return;
    }else{
      try {
        const res = await request({
          url: indexApi.payOrderApi(),
          method: "POST",
          data: reqTemplate
        });
        console.log("res========",res);
        if (this.data.payWay==1) {
          this.requestPayment(res.data)
          console.log("支付结果", res.data);
        } else {
          if (res.success==false) {
            Toast('余额不足！');
            return;
          }else{
            this.getpaydOrder()
          }
        }


       
       
      } catch (error) {
        console.error("Error:", error);
      }
    } 
  },


  //支付
  requestPayment(data) {
    const that = this;
    return new Promise((resolve, reject) => {
      wx.requestPayment({
        timeStamp: data.timeStamp, // 支付签名时间戳
        nonceStr: data.nonceStr, // 支付签名随机串
        package: data.packageStr, // 统一支付接口返回的 prepay_id 参数值
        signType: data.signType, // 签名算法，暂支持 MD5
        paySign: data.paySign, // 签名
        success(res) {
          console.log('支付成功');
          // 支付成功
          resolve(res);
          that.getpaydOrder()
          console.log("支付结果", res.data);
        },
        fail(err) {
          // 支付失败
          reject(err);
          console.log('支付失败',err);
          if (err.errMsg.includes("cancel")) {
            // 如果支付取消，跳转页面
            wx.switchTab({
              url: '/pages/order/index',
            });
          }
        },
        complete() {
          // 支付结果处理完成
        },
      });
    })
  },
  //支付成功更改订单状态
  async getpaydOrder() {
    console.log("this.date.orderId", this.data.orderId);
    const {orderId} =this.data
    const reqTemplate = {
      orderId: orderId
    }
    try {
      const res = await request({
        url: indexApi.paydOrder(),
        method: "POST",
        data: reqTemplate
      });

      console.log("更改订单状态", res.data);
      wx.navigateTo({
        url: `/packageOrder/pages/schedule/index?orderId=${orderId}`,
      })    
    } catch (error) {
      console.error("Error:", error);
    }
  },

});